package com.lx.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//通过加载配置文件流获得sqlSessionFactory，再获得sqlSession
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        //获取sqlSessionFactory对象
        try {
            //资源文件名（路径）
            String resource = "mybatis-config.xml";
            //获取流对象
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            //创建sqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取sqlSession对象的方法
    //SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
    public static SqlSession getSqlSession() {
         return sqlSessionFactory.openSession();
    }
}
